import React, { useState } from 'react'
import NavBar from '../../components/Navbar'
import './index.less'
import { Toast } from 'antd-mobile'
import appSdk from '../../utils/app_sdk'
// import { compareVersions, getVersion } from '../../utils/util';
import { updateAliAccount } from '../../api/mine'

function AddAli() {
  const [value, setValue] = useState('')
  const [saveStatus, setSaveStatus] = useState(false) //

  const handleClick = () => {
    if (!value) {
      Toast.show({
        content: '请填写支付宝账号'
      })
    }
    if (!saveStatus && value) {
      // if (compareVersions((getVersion() || '1.0.0'), '2.2.2') !== -1) {
      Toast.show({
        content: '授权请求中',
        icon: 'loading',
        maskClickable: false
      })
      appSdk('jumpToAliAuth', JSON.stringify({ ali_id: value }), (res) => {
        console.log('回调信息', res, '类型', typeof res)
        if (typeof res === 'string') {
          const { status, message } = JSON.parse(res)
          console.log('message', message)
          if (status === 'success') {
            setSaveStatus(true)
          }
          Toast.show({
            content: status === 'success' ? '授权成功' : '授权失败'
            // icon: 'none'
          })
        }
        if (typeof res === 'object') {
          const { status, message } = res
          console.log('message', message)
          if (status === 'success') {
            setSaveStatus(true)
          }
          Toast.show({
            content: status === 'success' ? '授权成功' : '授权失败'
            // icon: 'none'
          })
        }
      })
      // }
    }
  }

  const updateAccount = () => {
    updateAliAccount({
      ali_account: value
    })
      .then((res) => {
        Toast.show({
          content: '更新账号成功'
          // icon: 'none'
        })
        appSdk('backPress')
        console.log('更新账号成功')
      })
      .catch((err) => {
        Toast.show({
          content: err.message
        })
      })
  }

  const handleSave = () => {
    if (saveStatus) {
      console.log('提交')
      updateAccount()
    } else {
      Toast.show({
        content: '请先授权'
      })
    }
  }

  const onChange = (e) => {
    setValue(e.target.value)
  }

  return (
    <div className="add_ali_warp">
      <NavBar title="添加支付宝账户" />
      <div className="content">
        <div className="input_content">
          <input readOnly={saveStatus} onChange={onChange} className="input" placeholder="请填写支付宝账号" />
          <div className="auth" onClick={handleClick}>
            {saveStatus ? '已授权' : '跳转授权'}
          </div>
        </div>
      </div>
      <div className={`save ${!saveStatus ? 'disable' : ''}`} onClick={handleSave}>
        保存
      </div>
    </div>
  )
}

export default AddAli
